package com.tfswx.jcyw.ftp;

import com.tfswx.jcyw.ftp.config.Config;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

public class App {
    private static FtpServer server = null;

    public static void main(String[] args) throws FtpException {
        Config config = Config.getConfig();
        FtpServerFactory serverFactory = new FtpServerFactory();

        //设置访问用户名和密码还有共享路径
        BaseUser baseUser = new BaseUser();
        baseUser.setName(config.getUsername());
        baseUser.setPassword(config.getPassword());
        baseUser.setHomeDirectory("./ftp");

        List<Authority> authorities = new ArrayList<>();
        authorities.add(new WritePermission());
        baseUser.setAuthorities(authorities);

        serverFactory.getUserManager().save(baseUser);

        ListenerFactory factory = new ListenerFactory();
        factory.setPort(config.getPort()); //设置端口号 非ROOT不可使用1024以下的端口
        serverFactory.addListener("default", factory.createListener());

        server = serverFactory.createServer();
        server.start();
        System.out.println("ftp服务已启动");
    }

    @PreDestroy
    public void des() {
        server.stop();
        System.out.println("ftp服务已停止");
    }
}
